﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSiteFool.Models;

namespace WebSiteFool.Controllers
{
    [RestrictAuthorize]
    public class PictureController : BaseController
    {
        public FileContentResult Show(Guid id)
        {
            var picture = DbWorker.PictureRepository.GetById(id);
            return File(picture.Image, picture.ContentType);
        }

        [RestrictAuthorize(Roles = "SuperWoman")]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(Guid id)
        {
            DbWorker.PictureRepository.Delete(id);
            DbWorker.Save();
            return RedirectToAction("List");
        }

        [RestrictAuthorize(Roles = "SuperWoman")]
        public ActionResult List()
        {
            return View(DbWorker.PictureRepository.Get( orderBy: OrderByCreateDateDesc ));
        }

        [RestrictAuthorize(Roles = "SuperWoman")]
        [ValidateAntiForgeryToken]
        public ActionResult Create()
        {
            return PartialView("Create");
        }

        [HttpPost]
        [RestrictAuthorize(Roles = "SuperWoman")]
        [ValidateAntiForgeryToken]
        public ActionResult Create(PictureFile model)
        {
            if (!ModelState.IsValid)
            {
                return View("Create", model);
            }
            var file = model.File;
            var picture = new Models.Picture()
            {
                Id = Guid.NewGuid(),
                CreatedDate = DateTime.UtcNow,
                ContentType = file.ContentType,
                Name = model.Name
            };
            picture.Image = new byte[file.ContentLength];
            file.InputStream.Read(picture.Image, 0, file.ContentLength);
            DbWorker.PictureRepository.Insert(picture);
            DbWorker.Save();
            return RedirectToAction("List");
        }

        private IOrderedQueryable<Picture> OrderByCreateDateDesc(IQueryable<Picture> pictures)
        {
            return pictures.OrderByDescending(item => item.CreatedDate);
        }

    }
}
